//==========================================================================
// Copyright (c) 2000-2008,  Elastos, Inc.  All Rights Reserved.
//==========================================================================

#include <ddk.h>

#define THREADAMOUNT        100

IThread     *g_pIThread[THREADAMOUNT];

Int32 RunningThread1(void *pvPara)
{
    ThreadState     threadState;
    IThread         *pICurrentThread;
    ECode         ec;

    ec = DzGetCurrentThread(&pICurrentThread);
    if (FAILED(ec)) {
        kprintf("%d GetCurrentThread failed, the ec = 0x%08x\n", pvPara, ec);
        assert(0);

        return E_FAIL;
    }

    ec = pICurrentThread->GetState(&threadState);
    if (FAILED(ec)) {
        kprintf("%d GetState failed, the ec = 0x%08x\n", pvPara, ec);
        assert(0);

        goto Exit;
    }

    if (ThreadState_Running != threadState) {
        kprintf(">>>>>>>>>>>Error>>>>>>>>>>>>>>>>>>\n");
        assert(0);

        goto Exit;
    }

Exit:
    pICurrentThread->Release();

    while (1) {
        DzYield();
    }

    return E_FAIL;
}

Int32 RunningThread0(void *pvPara)
{
    ThreadState     threadState;
    ECode         ec;

    ec = g_pIThread[(uint_t)pvPara - 1]->GetState(&threadState);
    if (FAILED(ec)) {
        kprintf("%d GetState failed, the ec = 0x%08x\n",
                                            (uint_t)pvPara - 1, ec);
        assert(0);
    }

    if (ThreadState_Running != threadState) {
        kprintf(">>>>>>>>>>>Error>>>>>>>>>>>>>>>>>>\n");
        assert(0);

        goto Exit;
    }

Exit:
    while (1) {
        DzYield();
    }

    return E_FAIL;
}

EXTERN void GetStateRunningOnlyByMyself()
{
    ThreadState     threadState;
    ECode         ec;
    int             i;

    for (i = 0; i < THREADAMOUNT; i++) {
        if (i % 2) {
            ec = DzCreateKernelThread(RunningThread0, (void *)i, 0,
                                    (ThreadPriorityRank)0xFFFFEEEE, &g_pIThread[i]);
        }
        else {
            ec = DzCreateKernelThread(RunningThread1, (void *)i, 0,
                                    (ThreadPriorityRank)0xFFFFEEEE, &g_pIThread[i]);
        }

        if (FAILED(ec)) {
            kprintf("Create thread %d failed, the ec = 0x%08x\n",i,ec);
            assert(0);

            return;
        }

        DzYield();
    }

    DzSleep(100);

    for (i = 0; i < THREADAMOUNT; i++) {
        ec = g_pIThread[i]->GetState(&threadState);
        assert(NOERROR == ec);
        assert(ThreadState_Running == threadState);
    }

    for (i = 0; i < THREADAMOUNT; i++) {
        ec = g_pIThread[i]->Abort();
        assert(NOERROR == ec);

        g_pIThread[i]->Release();
    }
}
